let XIAOYDB = void 0
const DBTABLENAME = 'xiaoy_store'

const openDB = (DBName = 'xiaoy_db', version = 1) => {
  return new Promise((resolve, reject) => {
    const indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB
    const xiaoyDB = indexedDB.open(DBName, version)

    xiaoyDB.onerror = e => reject(e)
    xiaoyDB.onsuccess = e => {
      XIAOYDB = e.target.result
      resolve(e.target.result)
    }
    xiaoyDB.onupgradeneeded = e => {
      XIAOYDB = e.target.result
      if (!XIAOYDB.objectStoreNames.contains(DBTABLENAME)) {
        // 创建数据库表，设置key为主键，key自定义
        XIAOYDB.createObjectStore(DBTABLENAME, { keyPath: 'key' })
      }
    }
  })
}

export const removeDB = (DBName = 'xiaoy_db') => {
  return new Promise((resolve, reject) => {
    const indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB
    const deleteDB = indexedDB.deleteDatabase(DBName)
    deleteDB.onerror = e => reject(e)
    deleteDB.onsuccess = e => resolve(e.target?.result)
    deleteDB.onupgradeneeded = e => resolve(e.target?.result)
  })
}

// 新增表数据，openDB中直接创建了库表，故此方法不需要不用，新增数据时调用 update 即可
export const add = async (key, data, DBName, version) => {
  const DB = XIAOYDB ?? await openDB(DBName, version)

  return new Promise((resolve, reject) => {
    const objectStore = DB.transaction(DBTABLENAME, 'readwrite').objectStore(DBTABLENAME)
    const request = objectStore.add({ key, data })

    request.onsuccess = e => resolve(e.target?.result)
    request.onerror = e => reject(e)
  })
}

// 删除数据表中对应数据
export const remove = async (key, DBName, version) => {
  const DB = XIAOYDB ?? await openDB(DBName, version)

  return new Promise((resolve, reject) => {
    const objectStore = DB.transaction(DBTABLENAME, 'readwrite').objectStore(DBTABLENAME)
    const request = objectStore.delete(key)

    request.onsuccess = e => resolve(e.target?.result)
    request.onerror = e => reject(e)
  })
}

// 更新表数据，openDB中直接创建了库表，故新增和修改都调用此方法即可
export const update = async (key, data, DBName, version) => {
  const DB = XIAOYDB ?? await openDB(DBName, version)

  return new Promise((resolve, reject) => {
    const objectStore = DB.transaction(DBTABLENAME, 'readwrite').objectStore(DBTABLENAME)
    const request = objectStore.put({ key, data })

    request.onsuccess = e => resolve(e.target?.result)
    request.onerror = e => reject(e)
  })
}

// 读取删除数据表中对应数据
export const read = async (key, DBName, version) => {
  const DB = XIAOYDB ?? await openDB(DBName, version)

  return new Promise((resolve, reject) => {
    const objectStore = DB.transaction(DBTABLENAME).objectStore(DBTABLENAME)
    const request = objectStore.get(key)

    request.onsuccess = e => resolve(e.target?.result?.data)
    request.onerror = e => reject(e)
  })
}